import $api from "@/common/thcommon.js";
import md5 from '@/common/md5.min.js';
import util from '@/common/utils.js';
import config from '@/common/config.js';

export default {
	common:{
		method: 'GET',
		header:{
			// "content-type":"application/x-www-form-urlencoded",
			"content-type":"application/json; charset=utf-8",
		},
		data:{}
	},
	request(options = {}){
		options.method = options.method || this.common.method;
		options.header = options.header || this.common.header;
		// 验证权限token
		if (uni.getStorageSync('token')) {
			// 获取用户token
			options.header.token =  uni.getStorageSync('token');
			// options.data.token =  uni.getStorageSync('token');
			
		}
		// options.header.token =  '6d0055c4be59fb1942a3764896fcca03';
		options.url = config.hosts + options.url;

		return new Promise((reslove,reject)=>{
			uni.request({
				...options,
				success: (result) => {
					var data = result.data || {};//处理数据
					if(data.status == 401){
						$api.toast('验证失败,请重新登录')
						// setTimeout(()=>{
						// 	$api.openWindow('/pages/login/login');
						// },500)
						return						
					}
					
					// console.log(data)
					return reslove(data);// 成功
				},
				fail:(err)=>{
					console.log(options.url + '运行失败->' + JSON.stringify(err));
					uni.showToast({icon:'none',title:JSON.stringify(err)});
					return reject(err);//抛出异常的话如果调用的时候没有写catch会报错
					// return new Promise(() => {}) //中断promise链
				}
			});
		})
	},
	get(url,data={},options = {}){
		options.url = url;
		options.data = data;
		options.method = 'GET'
		return this.request(options)
	},	
	post(url,data={},options = {}){
		options.url = url;
		options.data = data;
		options.method = 'POST'
		// console.log(options.data)
		return this.request(options)
	},
	fileHost(filePath){
		return filePath?$store.state.host + filePath:'/static/images/default-image.png';
	},
	fileHostPro(filePath){
		return filePath?config.proHost + filePath:'/static/images/default-image.png';
	},
	upload(url,options = {}){
		options.url = $store.state.host + url;
		options.header = options.header || {};
		// options.header.token = $store.state.token;
		console.log(options.url +'=>上传照片看看');//打印
		return new Promise((res,rej)=>{
			uni.uploadFile({
				...options,
				success: (result) => {
					if(result.statusCode !== 200){
						uni.showToast({title: '上传失败图片',icon: 'none'});
						rej(result)
					}
					let data = JSON.parse(result.data)
					// #ifdef MP-WEIXIN
						data = JSON.parse(res.data);
					// #endif
					res(data)
				},
				fail:(err)=>{
					rej(err)
				}
			});
		})
	},
}